package com.demo.stats;

import com.alibaba.fastjson.JSON;
import com.demo.common.ErrCode;
import com.demo.controls.BaseController;
import com.jfinal.log.Log;

import java.util.ArrayDeque;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

//@Before(CrossOriginInterceptor.class)
public class StatsController extends BaseController {
    public static final int MAX_SIZE_CACHE = 60;
    public static Map<String, Queue<String>> map = new ConcurrentHashMap();
    public static UUID IDCreator = new UUID(System.currentTimeMillis(), System.currentTimeMillis());
    private Log log = Log.getLog(StatsController.class);
        String DEFAULT_CLIENT_ID = "default";

    public void index() {
        render("stats.html");
    }

    public void add() {

        String value = getPara("value");
        if (isEmpty(value)) {
            renderErr(ErrCode.IllegalParameter, "value is null");
        }

        String clientID = getPara("ID",DEFAULT_CLIENT_ID);
        Queue data = map.get(clientID);
        if (isEmpty(data)) {
            Queue<String> value1 = new ArrayDeque<>();
            map.put(clientID, value1);
            data = value1;
        }
        data.add(value);
        while (data.size() > MAX_SIZE_CACHE) {
            data.poll();
        }

        getResponse().addHeader("Access-Control-Allow-Origin","*");
        renderOK();
    }

    public void get() {
        Queue data = map.get(getPara("ID", DEFAULT_CLIENT_ID));
        if (isEmpty(data)) {
            Queue<String> objects = new ArrayDeque<>();
            data = map.put(DEFAULT_CLIENT_ID, objects);
        }

        getResponse().addHeader("Access-Control-Allow-Origin","*");
        renderJson(JSON.toJSONString(data));
    }
}


